const api = require("../utils/api.js");

exports.getList = function(that, apiName, data, itemSetter, success, chatMode) {
  // console.log("---" + that.data.location);
  if (!data.pageSize) {
    data.pageSize = 20;
  }
  data.pageNo = 1;
  var pageNo = that.data.pageNo;
  if (pageNo) {
    data.pageNo = pageNo;
    that.setData({
      waiting: true
    });
  } else {
    that.setData({
      pageNo: 1
    });
  }

  api.req(apiName, data)
    .then((data) => {
      wx.stopPullDownRefresh();
      // console.log(data);
      var l = that.data.list
      if (!l) {
        l = [];
      }

      var pageCount = 0;
      var totalRecords = 0;
      if (data.result.list) {
        pageCount = data.result.page.pageCount;
        totalRecords = data.result.page.totalRecords;
        for (var i = 0; i < data.result.list.length; i++) {
          // data.result.list[i].distanceStr = util.distanceFormat(data.result.list[i].distance);
          var item = data.result.list[i];
          item._index = i;
          if (itemSetter) {
            itemSetter(item);
          }
          if (chatMode) {
            l.unshift(data.result.list[i])
          } else {
            l.push(data.result.list[i])
          }
        }
      }

      that.setData({
        list: l,
        pageCount: pageCount,
        dataCount: totalRecords,
        waiting: false,
        empty: false,
        noMore: pageNo === pageCount,
        // remainCount: data.result.remainCount
      });
      var pageNo = that.data.pageNo;
      pageNo++;
      that.setData({
        hidden: true,
        pageNo: pageNo
      });

      if (l == null || l.length == 0) {
        that.setData({
          empty: true
        });
      }

      if (success) {
        success(data.result.list);
      }
    })
}

exports.isLastPage = function(that) {
  var pageNo = that.data.pageNo;
  var pageCount = that.data.pageCount;

  if (!pageNo || !pageCount) {
    return false;
  }

  return pageNo > pageCount;
}

exports.onPullDownRefresh = function(that) {
  console.log("下拉");
  that.refresh();
}

exports.onReachBottom = function(that) {
  console.log("上拉");
  if (!this.isLastPage(that)) {
    that.getList();
  } else {
    console.log("已经是最后一页");
    that.setData({
      waitingtype: 'NONE',
      waiting: true
    });
  }
}

exports.refresh = function(that) {
  that.setData({
    list: [],
    scrollTop: 0,
    pageNo: 1,
    pageCount: 1,
    waitingtype: '',
  });
  that.getList()
}

exports.scroll = function(that, event) {
  that.setData({
    scrollTop: event.detail.scrollTop
  });
}